package org.example.service;

import org.example.pojo.Client;
import org.example.repository.ClientRepository;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.util.List;

/**
 * @author 荆延龙
 * @version 1.0.0
 * data 2022/06/12
 */
@Service
public class ClientService {
    @Autowired
    ClientRepository clientRepository;

    /**
     * 获取或新建用户
     * @param id
     * @return
     */
    public void clientLogin(String id) throws Exception {
        id = id.toUpperCase();
        String trueMac = "([A-F0-9]{2}-){5}[A-F0-9]{2}";
        if (!id.matches(trueMac)){
            throw new Exception("请输入正确的MAC地址！");
        }
        Timestamp timestamp = new Timestamp(System.currentTimeMillis());
        Client client = clientRepository.findById(id).orElse(new Client(id, true));
        client.setAlive(true);
        clientRepository.saveAndFlush(client);
    }
    public void clientLogout(String id) throws Exception {
        id = id.toUpperCase();
        String trueMac = "([A-F0-9]{2}-){5}[A-F0-9]{2}";
        if (!id.matches(trueMac)){
            throw new Exception("请输入正确的MAC地址！");
        }
        Client client = clientRepository.findById(id).orElse(null);
        if (client==null) throw new Exception("用户不存在！");
        client.setAlive(false);
        clientRepository.saveAndFlush(client);
    }

    /**
     * 查询所有
     * @return
     */
    public List<Client> getAll(){
        return clientRepository.findAll();
    }
}
